package com.hk.mybatis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hk.mybatis.entity.IdEntity;
import com.hk.mybatis.service.EntityService;

import java.io.Serializable;

/**
 * @author miaoj
 */
public abstract class EntityServiceImpl<T extends IdEntity<ID>, ID extends Serializable, M extends BaseMapper<T>> extends ServiceImpl<M, T> implements EntityService<T, ID> {

    @Override
    public boolean exist(ID id) {
        final QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        return baseMapper.exists(queryWrapper);
    }

    @Override
    public T persist(T t) {
        t.setId(null);
        beforePersist(t);
        if (super.save(t)) {
            return getById(t.getId());
        }
        throw new RuntimeException("保存实体失败，详情请查看日志");
    }

    protected void beforePersist(T t) {
    }

    @Override
    public T update(T t) {
        if (t.getId() == null) {
            throw new RuntimeException("更新实体时,id不能为空");
        }
        if (exist(t.getId())) {
            beforeUpdate(t);
            if (updateById(t)) {
                return getById(t.getId());
            }
            throw new RuntimeException("更新实体失败,详情请查看日志");
        }
        throw new RuntimeException("更新实体时,id不能为空");
    }

    protected void beforeUpdate(T t) {
    }

    @Override
    public boolean removeById(String id) {
        return super.removeById(id);
    }
}
